<template>
  <div class="app-container">
    <SearchForm ref="queryFormRef" :model="queryParam" :inline="true" @reset="handleResetQuery" @search="handleQuery">
      <el-form-item prop="keywords" label="关键字">
        <el-input v-model="queryParam.keywords" placeholder="名称关键字" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <template #ext-btn v-h>
        <el-button type="success" v-hasPerm="['dict:add']" @click="handleOpenDialog()"
          :disabled="!dictItem?.dict_id"><i-ep-plus />新增</el-button>
        <el-button type="danger" v-hasPerm="['dict:del']" :disabled="selectionIds.length === 0 || !dictItem?.dict_id"
          @click="handleDelete()"><i-ep-delete />删除</el-button>
      </template>
    </SearchForm>
    <el-table ref="dataTableRef" v-loading="loading" :data="dictData" highlight-current-row border row-key="role_id"
      @row-click="handleRowClick" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="字典标签" prop="label" min-width="100" />
      <el-table-column label="字典值" prop="value" min-width="100" />
      <el-table-column label="排序" prop="dict_sort" width="70" align="center" />
      <el-table-column label="创建日期" prop="create_time" width="155">
        <template #default="scope">
          {{ formatDate(scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="80">
        <template #default="scope">
          <el-button type="primary" size="small" link @click="handleOpenDialog(scope.row)">
            <i-ep-edit />
          </el-button>
          <el-button type="danger" size="small" link @click="handleDelete(scope.row.role_id)">
            <i-ep-delete />
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination v-if="pagination.total > 0" v-model:total="pagination.total" v-model:page="pagination.current"
      v-model:limit="pagination.size" @pagination="handlePageChange" />
    <!--表单弹窗-->
    <DetailForm v-model="formModal.visible" :title="formModal.title" :selected-item="selectedItem"
      ref="dictDetailFormRef" @close="handleDialogClose" @submit="handleDialogSummit" />
  </div>
</template>

<script setup lang="ts">

defineOptions({
  name: "DictDetail",
  inheritAttrs: false,
})

import { DictVO } from "@/api/dict"
import DictDetailAPI, { DictDetailVO } from "@/api/dict-detail"
import { formatDate } from "@/utils";

// 定义接收的属性
interface Props {
  dictItem?: DictVO
}

const props = withDefaults(defineProps<Props>(), {})



const queryFormRef = ref(ElForm)
const dictDetailFormRef = ref(ElForm)

const loading = ref(false)

const selectedItem = ref<DictDetailVO>({})

const selectionIds = ref<number[]>([])

const queryParam = reactive({
  keywords: undefined,
  enabled: undefined,
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
})

//构建storex的查询条件
const queryConditon = reactive<QueryCondition>({
  paging: {
    current: pagination.current,
    size: pagination.size,
  },
  sorts: [{
    field: "create_time",
    sort_asc: false
  }]
})

// 字典项表格数据
const dictData = ref<DictVO[]>()

// 表单弹窗
const formModal = reactive({
  title: "",
  visible: false,
})


// 字典项项弹窗
const detailModal = reactive({
  title: "",
  visible: false,
})


const handlePageChange = () => {
  queryConditon.paging = { ...pagination }
  getPage()
}


/** 分页查询 */
const getPage = () => {
  loading.value = true
  DictDetailAPI.getPage(queryConditon).then((res) => {
    const { status, data } = res
    if (status === 200) {
      dictData.value = data.records
      pagination.total = data.total
    }
  }).finally(() => {
    loading.value = false
  })
}

/** 查询 */
const handleQuery = () => {
  queryConditon.and = []
  if (queryParam.keywords) {
    queryConditon.and?.push(
      { field: "label", op: "like", value: `%${queryParam.keywords}%` }
    )
  }
  if (props.dictItem?.dict_id) {
    queryConditon.and?.push(
      { field: "dict_id", op: "=", value: props.dictItem?.dict_id }
    )
  }
  queryConditon.paging = {
    current: 1,
    size: pagination.size
  }
  getPage()
}

/** 重置查询 */
const handleResetQuery = () => {
  queryParam.keywords = undefined
  pagination.current = 1
  handleQuery()
}


/** 行复选框选中记录选中ID集合 */
const handleSelectionChange = (selection: any) => {
  selectionIds.value = selection.map((item: any) => item.detail_id)
}

/** 选择行 */
const handleRowClick = (row: DictDetailVO) => {
  selectedItem.value = { ...row }
}


/** 打开字典项弹窗 */
const handleOpenDialog = (row?: DictDetailVO) => {
  if (row && row.detail_id) {
    formModal.title = "编辑字典项"
  } else {
    selectedItem.value = {
      dict_id: props.dictItem?.dict_id,
      dict_sort: 1
    }
    formModal.title = "新增字典项"
  }
  formModal.visible = true
}
/** 字典项弹窗提交 */
const handleDialogSummit = () => {
  formModal.visible = false
  handleQuery()
}

/** 关闭字典项弹窗 */
const handleDialogClose = () => {
  formModal.visible = false
}


/** 删除字典项 */
const handleDelete = (detailId?: number) => {
  const detailIds = detailId ? [detailId] : selectionIds.value
  if (!detailIds) {
    ElMessage.warning("请勾选删除项")
    return
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true
      const deleteCondition: QueryCondition = {
        "_cond": { and: [{ field: "detail_id", op: "in", value: detailIds }] }
      }
      DictDetailAPI.deleteBy(deleteCondition).then((res) => {
        if (res.status === 200) {
          ElMessage.success("删除成功")
          handleQuery()
        }
      }).finally(() => (loading.value = false))
    },
    () => { }
  )
}
//表单传递数据
watch(() => props.dictItem, (newVal: any, oldVal) => {
  if (props.dictItem?.dict_id) {
    handleQuery()
  }
}, { immediate: true, deep: true })

</script>
